<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\GuildOp;
use App\Http\Controllers\Controller;
use App\Model\AdminUser;
use App\Model\AdminUsers;
use App\Model\Guild\Guild;
use App\Model\Guild\GuildAccount;
use App\Model\Guild\GuildBalance;
use App\Model\Guild\GuildHost;
use App\Model\Guild\GuildWithdrawal;
use App\Model\UserProfile;
use App\Util\InfoUtil;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Log;

/**
 * 代理管理
 */
class GuildController extends Controller
{
    use ModelForm;

    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header('推广员列表');
            $content->description('');
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('推广员详情');
            $content->description('');
            $content->body($this->form('edit', $id)->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('添加推广员');
            $content->description('');
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        if(Admin::user()->id == 48) return [];
        $isTmp = Admin::user()->id == env('TEMP_ACCOUNT_ID', 7);
        return Admin::grid(Guild::class, function (Grid $grid) use ($isTmp) {
            $self = $this;
            if(Admin::user()->id == 48 || in_array(Admin::user()->id,[49,50,51])){
                $grid->model()->where('admin_id',Admin::user()->id);
            }
            $grid->model()->orderBy('id', 'desc');
            $grid->created_at('添加日期')->display(function ($time) {
                return !$time ? '-' : date('Y-m-d', strtotime($time));
            });
            $grid->name('推广员名');
            $grid->guild_id('推广员ID');

            $grid->user_profile_id('推广员外部id')->editable();

            $grid->manager_phone('联系方式')->display(function ($data) {
                return !$data ? '-' : substr($data, 0, 3) . "****" . substr($data, -4);
            });

            $grid->guild_share_ratio('推广方分成')->editable();

            $grid->host_share_ratio('推广成员分成');
            $grid->host_num('推广成员人数')->display(function ($data) {
                return GuildHost::getHostNum($this->id);
            });
            $grid->account('账号/密码')->display(function ($data) {
                return "{$this->login_account}<br/>{$this->login_pwd}";
            });
            $grid->status('账号状态')->display(function ($data) {
                return $data ? '已启用' : '已禁用';
            });
            $grid->admin_id('维护管理员')->editable('select', AdminUsers::pluck('name', 'id')->toArray());

            //禁用导出
//            $grid->disableExport();
            //禁用行选择
            $grid->disableRowSelector();
            $grid->filter(function ($filter) {
                $filter->expand();
                $filter->disableIdFilter();
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('id', '代理')->select('/get_guilds');
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('status', '有效状态')->select([0 => '无效', 1 => '有效']);
                });
                $adminId = Admin::user()->id;
                $flag = false;
               if($adminId == 48 || in_array($adminId,[49,50])) $flag = true;
                if(!$flag){
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('admin_id', '维护管理员')->select(Guild::getAdminids());
                    });
                }
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) use ($isTmp) {
                $actions->disableDelete();
                $actions->disableView();
                // $actions->disableEdit();
                $actions->append(new GuildOp(
                    $actions->getKey(),
                    $actions->row,
                    'guild_op'
                ));
            });
        });
    }

    /**
     * Make a form builder.
     * @return Form
     */
    protected function form($mode = '', $id = '')
    {
        return Admin::form(Guild::class, function (Form $form) use ($mode, $id) {

            $form->column(1 / 2, function ($form) {
                $form->text('name', '代理名称')->required();
                if ($form->isCreating()) {
                    $form->text('manager_phone', '负责人联系方式')->required();
                } else {
                    $form->display('manager_phone', '负责人联系方式')->with(function ($data) {
                        return mb_substr($data, 0, 3) . '****' . mb_substr($data, -4);
                    });
                }

                $form->text('user_profile_id', '公会长id')->default(0)->required();

                $form->text('comp_name', '公司主体名')->default('');
                $form->text('bank_account', '银行卡账号')->default('');
                $form->multipleImage('credit_pics', '公司营业资质照')->uniqueName()->removable();
                $form->text('guild_share_ratio', '代理分成比例')->style('width', '80px')->default(0.1)->required();
                // $form->text('host_share_ratio', '女用户分成比例（已失效）')->style('width', '80px')->default(0.1)->required();
            });

            $form->column(1 / 2, function ($form) {
                $form->text('manager_name', '负责人姓名')->required();
                $form->text('manager_id_card', '负责人身份证号')->default('');
                $form->text('comp_credit_code', '企业信用代码')->default('');
                $form->text('bank_id', '收款银行')->default('');
                $form->text('alipay_account', '支付宝账号');
                // $form->multipleImage('id_card_pics', '身份证照片')->uniqueName()->removable();
                $adminId = Admin::user()->id;
                $flag = false;
               if($adminId == 48 || in_array($adminId,[49,50])) $flag = true;
                if($flag){
                    $form->select('admin_id', '维护管理员')->options(AdminUsers::where('id',$adminId)->pluck('name', 'id')->toArray())->required();
                }else{
                    $form->select('admin_id', '维护管理员')->options(AdminUsers::pluck('name', 'id')->toArray())->required();
                }
                $adminId = Admin::user()->id;
                if($adminId != 50){
                    $form->select('invite_share_ratio', '是否分成邀请奖励')->options(['0' => '禁用', '0.05' => '启用']);
                }


            });

            $form->saving(function (Form $form) {
                if (!empty($form->guild_share_ratio)){
                    $maxRatio = 0.5;

                    if ($form->guild_share_ratio > $maxRatio){
                        throw new \Exception('代理分成比例不能超过:'.$maxRatio * 100 .'%');
                        return ;
                    }
                }

                $model = $form->model();

                !$form->comp_name && $form->comp_name = '';
                !$form->bank_account && $form->bank_account = '';
                !$form->manager_id_card && $form->manager_id_card = '';
                !$form->comp_credit_code && $form->comp_credit_code = '';
                !$form->bank_id && $form->bank_id = '';
                !$form->alipay_account && $form->alipay_account = '';
                !$form->id_card_pics && $form->id_card_pics = [];
                !$form->credit_pics && $form->credit_pics = [];

            });

            //生成账号，密码
            $form->saved(function (Form $form) {



                $model = $form->model();
                //代理ID
                if (empty($model->login_account) && empty($model->login_pwd)){
                    $guildId = Guild::buildGuildId($model->id);
                    //代理账号
                    $pwd = Guild::buildPwd($model->name);

                    $account = Guild::updateAccount($model->id, $guildId, $guildId, $pwd);
                    //运营后台账号
                    AdminUser::createUser($guildId, $pwd, $model->name, AdminUser::ROLE_GUILD);
                }

                if (!empty($form->user_profile_id)){
                    $profile = UserProfile::getInfoByProfileId($form->user_profile_id);
                    if (empty($profile)){
                        throw new \Exception('查无此人:用户id='.$form->user_profile_id);
//                    return InfoUtil::lineEditErr('查无此人:用户id='.$form->user_profile_id);
                    }
                    $guild = Guild::where('id',$model->id)->first();
                    $user = Guild::getUserId($profile->user_id);
                    if (!empty($user) && $user->id != $model->id){
                        throw new \Exception('外部为' . $form->user_profile_id . '的用户已经绑定公会:' . $user->guild_id);
//                    return InfoUtil::lineEditErr('外部为' . $form->user_profile_id . '的用户已经绑定公会:' . $user->guild_id);
                    }
                    Guild::where('id',$model->id)->update([
                        'user_id' => $profile->user_id
                    ]);

                    $balance = GuildBalance::where('guild_manage_id',$model->id)->first();
                    if (!empty($balance)){
                        GuildBalance::where('guild_manage_id',$model->id)->update([
                            'user_id' => $profile->user_id
                        ]);
                    }

                    if (!empty($guild) && !empty($guild->user_id)){
                        $accountNum = GuildWithdrawal::where('user_id',$guild->user_id)->count();
                        if ($accountNum > 0){
                            GuildAccount::where('user_id',$guild->user_id)->update([
                                'user_id' => $profile->user_id
                            ]);
                        }


                        $withNum = GuildWithdrawal::where('user_id',$guild->user_id)->count();
                        if ($withNum > 0){
                            GuildWithdrawal::where('user_id',$guild->user_id)->update([
                                'user_id' => $profile->user_id
                            ]);
                        }
                    }
                }



            });

            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }

    function guild_op()
    {
        $id = request('id');
        $status = intval(request('status'));
        $record = Guild::find($id);
        if (!$record) return ['ret' => -1, 'message' => '该代理
        记录不存在'];
        $record->update(['status' => $status]);
        return ['ret' => 0, 'message' => '操作成功！'];
    }
}
